﻿//
// *************************************************************************************
// WP-Framework
//
// Developed by 
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2013 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// *************************************************************************************
//
//
			

using System;
using System.Collections.Generic;
using KretschIT.WP_Fx.EasyMoq.Exceptions;
using KretschIT.WP_Fx.Core.Validation;

namespace KretschIT.WP_Fx.EasyMoq
{
    public abstract class BaseMockFactory : IMockFactory 
    {
        private readonly IDictionary<Type, Func<object>> mapping = new Dictionary<Type, Func<object>>(); 

        public IMock<T> Mock<T>() where T : class
        {
            return new Mock<T>(this);
        }

        void IMockFactoryRegistration.Register<T, TMockable>(Func<TMockable> create)
        {
            this.mapping.Add(typeof(T), () => create());
        }

        internal T Resolve<T>(IHandler<T> handler) where T : class
        {
            It.IsNotNull(() => handler);

            var type = typeof(T);
            if (this.mapping.ContainsKey(type))
            {
                return this.Create(type, handler);
            }
            throw new MissingMappingException();
        }

        private T Create<T>(Type type, IHandler<T> handler) where T : class
        {
            var mockableType = this.mapping[type];
            var instance = mockableType();
            ((Mockable<T>)instance).Handler = handler;
            return (T)instance;
        }
    }
}
